package es.uem.listaactividades;

import java.io.IOException;


import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.media.MediaPlayer.OnCompletionListener;


public class PruebaMediaPlayer extends Activity implements OnCompletionListener  {
	String TAG = "PruebaMediaPlayer";
	MediaPlayer mediaPlayer;
	boolean isPrepared = false;
	boolean isLoad = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_prueba_media_player);

		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		mediaPlayer = new MediaPlayer();
	
	}

	public void play(View view) {

		if (mediaPlayer.isPlaying())
			return;
		try {
			synchronized (this) {
				if (!isPrepared)
				{
					if (!isLoad)
					{
					AssetManager assetManager = getAssets();
					AssetFileDescriptor descriptor = assetManager
						.openFd("Big_Freeze.mp3");

					mediaPlayer.setDataSource(descriptor.getFileDescriptor(),
						descriptor.getStartOffset(), descriptor.getLength());
					
					isLoad = true;
					}
					mediaPlayer.prepare();
				    mediaPlayer.start();
				    isPrepared = true;
					mediaPlayer.setOnCompletionListener(this);
				}
			}
		} catch (IllegalStateException e) {		
			Log.d(TAG, e.getMessage());
		} catch (IOException e) {			
			Log.d(TAG, e.getMessage());
		}

	}

	
	public void stop(View view) {
		mediaPlayer.stop();		
		synchronized (this) {
			isPrepared = false;
		}
	}

	protected void onResume() {
		super.onResume();
		if (mediaPlayer != null) {
			mediaPlayer.start();
		}
	}

	protected void onPause() {
		super.onPause();
		if (mediaPlayer != null) {
			mediaPlayer.pause();
			if (isFinishing()) {
				mediaPlayer.stop();
				mediaPlayer.release();
			}
		}
	}

	public void onCompletion(MediaPlayer mp) {
		synchronized (this) {
			isPrepared = false;
		}
		finish();
		
	}

	
	
	
}